//
//  OAuthViewController.swift
//  01_新浪微博
//
//  Created by 黄蓉 on 15/12/13.
//  Copyright © 2015年 黄蓉. All rights reserved.
//

import UIKit
import AFNetworking
import SVProgressHUD
class OAuthViewController: UIViewController, UIWebViewDelegate {

      
    var oAuthWebView: UIWebView?
    
    override func viewDidLoad() {
        super.viewDidLoad()
        oAuthWebView?.delegate = self
        loadOAuthPage()
        
        
        
    }
    //将访客页面设置为webview,设置nav的相关信息
    override func loadView() {
        oAuthWebView = UIWebView()
        view = oAuthWebView
        title = "sina"
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "关闭", style: UIBarButtonItemStyle.Plain, target: self, action: "close")
         navigationItem.rightBarButtonItem = UIBarButtonItem(title: "自动填充", style: UIBarButtonItemStyle.Plain, target: self, action: "autoLoad")
        
        
    }
    
    //自动登录
    @objc  private func autoLoad() {
        
        let jsString = "document.getElementById('userId').value = 'leiggee@126.com' ,document.getElementById('passwd').value = 'oyonomg' "
        
        oAuthWebView?.stringByEvaluatingJavaScriptFromString(jsString)
        
      
    }
    
    
    //加载授权页面
    private    func loadOAuthPage() {
        
        let urlString = "https://api.weibo.com/oauth2/authorize?client_id=\(WB_Client)&redirect_uri=\(WB_Redirect_URI)"
        
        let url = NSURL(string: urlString)!
        
        oAuthWebView?.loadRequest(NSURLRequest(URL: url))
        
    }
    
  
    ///初始地址URL: https://api.weibo.com/oauth2/authorize?client_id=1407267207&redirect_uri=http://www.baidu.com }
    ///  成功的地址: { URL: https://api.weibo.com/oauth2/authorize }
    
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {

        let urlStr = request.URL!.absoluteString
       
        //如果不包含回调url的字符串就继续加载
        if !(urlStr.hasPrefix(WB_Redirect_URI)) {
            return true
        }
        
//        print(request)
        //如果是新浪的,就继续加载
        //如果是回调地址就判断是否有授权码
        //获取请求url中的查询字符串
        let query = request.URL!.query!
        let codeStr = "code="
        if query.hasPrefix(codeStr) {
            print("请求授权码")
        let formLength = (codeStr as NSString).length
        let code = (query as NSString).substringFromIndex(formLength)
            
           UserAccountModel().loadAccessToken(code, finish: { (isSuccess) -> () in
                //登录成功,dismiss
                self.dismissViewControllerAnimated(false, completion: { () -> Void in
                NSNotificationCenter.defaultCenter().postNotificationName(notification, object: "welcomme")
                })
                
                
            })
//        print(code)
        }else{
            print("取消授权")
            close()
           
        }
        return true
    }
       
    
    func webViewDidStartLoad(webView: UIWebView) {
    SVProgressHUD.show()
    
    }
    func webViewDidFinishLoad(webView: UIWebView) {
        SVProgressHUD.dismiss()
    }
    
 @objc private  func close() {
        dismissViewControllerAnimated(true) { () -> Void in
            
        }
    }
    

}
